/*
 * Raita.cpp
 *
 *  Created on: 31-08-2013
 *      Author: Krzychu
 */

#include "Raita.h"

#include "Config.h"

#include <stdio.h>
#include <string.h>

Raita::Raita()
{

}

Raita::~Raita()
{

}

std::string Raita::getName()
{
	return "Raita";
}

searchResult Raita::execute(std::string text, std::string pattern)
{
	searchResult result;
	result.iterationsTaken = 0;

	int textLength = text.length();
	int patternLength = pattern.length();
	const char* textChar = text.c_str();
	const char* patternChar = pattern.c_str();

	/* Preprocessing */
	int* bmBc = pre_bad_character_shift(pattern);
	char firstCh = pattern[0];
	const char* secondCh = patternChar + 1;
	char middleCh = pattern[patternLength / 2];
	char lastCh = pattern[patternLength - 1];
	char c;

	/* Searching */
	int j = 0;
	while (j <= textLength - patternLength)
	{
		result.iterationsTaken++;
		c = text[j + patternLength - 1];
		if (lastCh == c && middleCh == text[j + patternLength / 2] && firstCh == text[j]
				&& memcmp(secondCh, textChar + j + 1, patternLength - 2) == 0)
		{
			result.positionsFound.push_back(j);
			if (Config::getInstance()->getFindOneOccurence())
			{
				return result;
			}
		}
		j += bmBc[c];
	}

	return result;
}

